/*
 * @Description: 试妆推广H5 mixin
 * @Author: kanglin
 * @Date: 2018-05-11 17:21:40
 * @Copyright: Created by Panxsoft.
 */

const COUPON = '/api/may-promo/promo-coupon';
const USER_INFO_API = '/open-wechat/wechat-user/';
const AUTH_SCOPE = 'snsapi_base'; // snsapi_userinfo 或 snsapi_base 默认 base 如失败则自动跳转 userinfo
const OAUTH_PATH = '/open-wechat/oauth';
const OPEN_ID_API = '/open-wechat/openid';

/* global Qs, axios, AUTHORIZER_APPID */
window.mayPromoMixin = {
  methods: {
    /**
     *  解析open id
     */
    resolveOpenId() {
      const self = this;
      return new Promise(((resolve) => {
        const urlInfo = Qs.parse(window.location.search.replace(/^\?/, ''));
        if (urlInfo.openid) {
          // alert(urlInfo.openid);
          return resolve(urlInfo.openid);
        }
        return resolve(self.fetchOpenId());
      }));
    },

    /**
     *  请求 openid
     */
    fetchOpenId() {
      const self = this;
      return axios.get(OPEN_ID_API)
        .then((response) => {
          if (response.data.code !== 0) {
            self.redirectToOAuthPage();
            return null;
          }

          return response.data.openid;
        });
    },

    /**
     * 重定向
     */
    redirectToOAuthPage() {
      window.location.href = this.assembleOAuthUrl();
    },

    /**
     * 组合参数
     * @return {string}
     */
    assembleOAuthUrl() {
      const currentUrl = encodeURIComponent(window.location.href);
      return `${OAUTH_PATH
      }?redirect_url=${currentUrl
      }&appid=${AUTHORIZER_APPID
      }&scope=${AUTH_SCOPE}`;
    },

    /**
     * @param {string} openid
     * @return {object} user_info
     */
    fetchUserInfo(openid) {
      return axios.get(USER_INFO_API + openid)
        .then((response) => {
          if (response.data.code !== 0) {
            throw new Error(response.data.error);
          } else {
            return response.data.wechat_user;
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },

    /**
     * 请求卡券列表
     * @param params
     */
    fetchCouponIndex(params) {
      return axios.get(COUPON, { params })
        .then((response) => {
          if (response.data.code !== 0) {
            throw new Error(response.data.error);
          } else {
            return response.data.coupon_lists;
          }
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },

};
